package com.jww.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jww.domain.User;
import com.jww.service.UserService;
import com.jww.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {
    private UserService service = new UserServiceImpl();
    private ObjectMapper mapper = new ObjectMapper();

    public void selectAll(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {

        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        List<User> users = service.selectAll();

        try {
            String json = mapper.writeValueAsString(users);
            //响应json数据
            resp.getWriter().write(json);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //新增功能
    public void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");
        // 1 获取页面数据
        String userStr = req.getParameter("userStr");
        System.out.println(userStr);

        // json数据转换成对象
        User user = mapper.readValue(userStr, User.class);
        service.save(user);
    }

    //修改
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //设置字符集
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        //获取
        String user = req.getParameter("user");

        //json数据转换成数据
        User users = mapper.readValue(user, User.class);
        service.update(users);

    }

    //删除
    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        resp.setContentType("text/html;charset=UTF-8");
        req.setCharacterEncoding("UTF-8");

        //获取ids
        String ids = req.getParameter("ids");
        service.deleteByIds(ids);

    }


}
